using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Microsoft.Extensions.Logging;
using Volo.Abp;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Modularity;
using System.Diagnostics;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using System.Net.Mime;

namespace MatrixFramework.Shared.Application.Monitoring
{
    /// <summary>
    /// 简化的服务配置模板
    /// 提供基础的健康检查和监控功能
    /// </summary>
    public static class SimpleServiceTemplate
    {
        /// <summary>
        /// 配置标准化的服务端点
        /// </summary>
        /// <param name="context">服务配置上下文</param>
        /// <param name="serviceName">服务名称</param>
        public static void ConfigureStandardEndpoints(ServiceConfigurationContext context, string serviceName)
        {
            var services = context.Services;
            var configuration = context.Services.GetConfiguration();

            // 添加健康检查
            services.AddHealthChecks()
                .AddCheck("self", () => HealthCheckResult.Healthy($"{serviceName} 运行正常"));

            // 配置日志
            services.AddLogging(builder =>
            {
                builder.ClearProviders();
                builder.AddConsole();
                builder.AddDebug();
            });
        }

        /// <summary>
        /// 配置应用程序初始化管道
        /// </summary>
        /// <param name="context">应用初始化上下文</param>
        /// <param name="serviceName">服务名称</param>
        public static void ConfigureStandardPipeline(ApplicationInitializationContext context, string serviceName)
        {
            var app = context.GetApplicationBuilder();
            var env = context.GetEnvironment();
            var configuration = context.GetConfiguration();

            // 配置路由
            app.UseRouting();

            // 配置端点
            app.UseEndpoints(endpoints =>
            {
                // 健康检查端点
                endpoints.MapHealthChecks("/health");

                // API信息端点
                endpoints.MapGet("/api/info", () => new
                {
                    Service = serviceName,
                    Version = configuration.GetValue<string>("Service:Version", "1.0.0"),
                    Environment = env.EnvironmentName,
                    HostName = Environment.MachineName,
                    ProcessId = Environment.ProcessId,
                    StartTime = System.Diagnostics.Process.GetCurrentProcess().StartTime,
                    Timestamp = DateTime.UtcNow
                });

                // 版本信息端点
                endpoints.MapGet("/version", () => new
                {
                    Service = serviceName,
                    Version = configuration.GetValue<string>("Service:Version", "1.0.0"),
                    Framework = Environment.Version.ToString(),
                    Platform = Environment.OSVersion.ToString()
                });
            });
        }

        /// <summary>
        /// 添加标准化异常处理
        /// </summary>
        /// <param name="context">应用初始化上下文</param>
        public static void ConfigureStandardExceptionHandling(ApplicationInitializationContext context)
        {
            var app = context.GetApplicationBuilder();

            // 简化的异常处理中间件
            app.UseExceptionHandler(errorApp =>
            {
                errorApp.Run(async context =>
                {
                    context.Response.StatusCode = 500;
                    context.Response.ContentType = "application/json";

                    var errorResponse = new
                    {
                        error = new
                        {
                            code = "INTERNAL_SERVER_ERROR",
                            message = "An internal server error occurred",
                            timestamp = DateTime.UtcNow,
                            traceId = Activity.Current?.TraceId.ToString()
                        }
                    };

                    await context.Response.WriteAsJsonAsync(errorResponse);
                });
            });
        }

        /// <summary>
        /// 获取标准配置模板
        /// </summary>
        /// <returns>标准配置字典</returns>
        public static Dictionary<string, object> GetStandardConfigurationTemplate()
        {
            return new Dictionary<string, object>
            {
                // 服务配置
                ["Service"] = new Dictionary<string, object>
                {
                    ["Name"] = "YourServiceName",
                    ["Version"] = "1.0.0",
                    ["Namespace"] = "MatrixFramework"
                },

                // 健康检查配置
                ["HealthChecks"] = new Dictionary<string, object>
                {
                    ["Self"] = new Dictionary<string, object>
                    {
                        ["Delay"] = 5,
                        ["Timeout"] = 30,
                        ["Period"] = 30
                    }
                },

                // 日志配置
                ["Logging"] = new Dictionary<string, object>
                {
                    ["LogLevel"] = new Dictionary<string, object>
                    {
                        ["Default"] = "Information",
                        ["Microsoft"] = "Warning",
                        ["Microsoft.EntityFrameworkCore"] = "Warning"
                    }
                }
            };
        }
    }
}